# 区分头文件和源文件
function(protobuf_generator proto_dir inc_dir src_dir)
    if(NOT Protobuf_PROTOC_EXECUTABLE)
        find_program(Protobuf_PROTOC_EXECUTABLE NAMES protoc)
        if(NOT Protobuf_PROTOC_EXECUTABLE)
            message(FATAL_ERROR "protoc not found")
        endif()
    endif()

    file(GLOB PROTO_FILES
      "${proto_dir}/*.proto"
    )

    foreach(FIL ${PROTO_FILES})
        get_filename_component(FIL_NAME ${FIL} NAME_WE)
        execute_process(
            COMMAND ${Protobuf_PROTOC_EXECUTABLE}
            -I ${proto_dir}
            --cpp_out=${inc_dir}
            --cpp_out=${src_dir}
            "${FIL_NAME}.proto"
        )

        file(REMOVE "${inc_dir}/${FIL_NAME}.pb.cc" "${src_dir}/${FIL_NAME}.pb.h")
    endforeach()
endfunction()

# 生成所有代码到同一目录
function(protobuf_generator_grpc proto_dir code_dir)
    if(NOT Protobuf_PROTOC_EXECUTABLE)
        find_program(Protobuf_PROTOC_EXECUTABLE NAMES protoc)
        if(NOT Protobuf_PROTOC_EXECUTABLE)
            message(FATAL_ERROR "protoc not found")
        endif()
    endif()

    if(NOT GRPC_CPP_PLUGIN)
        find_program(GRPC_CPP_PLUGIN NAMES grpc_cpp_plugin)
        if(NOT GRPC_CPP_PLUGIN)
            message(FATAL_ERROR "grpc_cpp_plugin not found")
        endif()
    endif()

    file(GLOB PROTO_FILES
      "${proto_dir}/*.proto"
    )

    foreach(FIL ${PROTO_FILES})
        get_filename_component(FIL_NAME ${FIL} NAME_WE)
        execute_process(
            COMMAND ${Protobuf_PROTOC_EXECUTABLE}
            -I ${proto_dir}
            --grpc_out=${code_dir}
            --cpp_out=${code_dir}
            --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN}
            "${FIL_NAME}.proto"
        )
    endforeach()
endfunction()